package com.changhong.framework.sdfs.namenode.server.builder;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * 通过java SPI扩展机制来加载对象
 * @author Summer
 */
public class ServiceManager {

    /**
     * 获取第一个对象
     * @param clazz
     * @param <S>
     * @return
     */
    public static <S> S loadHead(Class<S> clazz) {
        Iterator<S> iterator = loadAll(clazz);
        if (!iterator.hasNext()) {
            throw new IllegalStateException(String.format(
                    "No implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!",
                    clazz.getName()));
        }
        return iterator.next();
    }

    /**
     * 获取当前类型所有的实例对象
     * @param clazz 接口类型
     * @param <S> 泛型
     * @return 返回相关的类型对象
     */
    public static <S> Iterator<S> loadAll(Class<S> clazz) {
        ServiceLoader<S> loader = ServiceLoader.load(clazz);
        return loader.iterator();
    }
}
